import { onMounted, onBeforeUnmount } from "vue";

const useDrag = emits => {
  let isBaseMapDragging = false;
  let cursorPosition = { x: 0, y: 0 };
  let originScrollLeft = 0;
  let originScrollTop = 0;
  // 背景图片缩放比例
  let scale = 1;
  let offEvents = null;
  function eventsInit({ baseMap, content }) {
    baseMap.addEventListener("mousedown", baseMapMouseDownEvent);
    baseMap.addEventListener("wheel", baseMapWheelEvent);
    // 鼠标移动，判断是否正在拖拽，是哪个元素正在拖拽
    // 为了防止鼠标移动时，移动到元素的范围之外，
    // 需要将事件绑定在document上
    document.addEventListener("mousemove", documentMousemoveEvent);

    // 鼠标抬起，停止拖拽
    document.addEventListener("mouseup", documentMouseupEvent);

    function baseMapMouseDownEvent(e: MouseEvent) {
      isBaseMapDragging = true;
      // 记录鼠标相对于浏览器可视区域的x，y距离
      cursorPosition.x = e.clientX;
      cursorPosition.y = e.clientY;
      // 记录mousedown时，content已经滚动的距离
      originScrollLeft = content.scrollLeft;
      originScrollTop = content.scrollTop;
    }
    function baseMapWheelEvent(e: MouseEvent) {
      const { deltaY } = e;
      let preScale = scale;

      if (deltaY > 0) {
        // 向下滚 缩小
        scale -= 0.2;
        // 缩小最小值为1（可根据需求更改）
        if (scale < 1) scale = 1;
        // baseMap.style.transform = `translateZ(0) scale(${scale})`;
        emits("changeCompPicScale", { pre: preScale * 100, cur: scale * 100 });
      } else if (deltaY < 0) {
        // 向上滚 放大
        scale += 0.2;
        // 放大最大值为2（可根据需求更改）
        if (scale > 3) scale = 3;
        // baseMap.style.transform = `translateZ(0) scale(${scale})`;
        emits("changeCompPicScale", { pre: preScale * 100, cur: scale * 100 });
      }

      // dy = 50 * (scale / preScale - 1);
      // dx = 50 * (scale / preScale - 1);
      // // 这里注意scale缩放比例
      // point.style.left = (parseFloat(point.style.left) / preScale) * scale + dx / 2 + "px";
      // point.style.top = (parseFloat(point.style.top) / preScale) * scale + dy / 2 + "px";
      // console.log(point.style.left, dx);
      // 阻止默认行为，防止缩放图片时使页面滚动
      e.preventDefault();
    }
    function documentMousemoveEvent(e) {
      // pic正在拖拽
      if (isBaseMapDragging) {
        // 计算鼠标相对于原始位置的偏移量
        let changeX = e.clientX - cursorPosition.x;
        let changeY = e.clientY - cursorPosition.y;

        // 让content也滚动相同的偏移量
        // 值得注意的是，鼠标移动的方向数值与scrollLeft移动方向的数值是相反的，
        // 所以不是加上changX，而是减去changeY。scrollTop同理。
        content.scrollLeft = originScrollLeft - changeX;
        content.scrollTop = originScrollTop - changeY;
      }
    }
    function documentMouseupEvent() {
      isBaseMapDragging = false;
    }
    const offEvents = () => {
      baseMap.removeEventListener("mousedown", baseMapMouseDownEvent);
      baseMap.removeEventListener("wheel", baseMapWheelEvent);
      document.removeEventListener("mousemove", documentMousemoveEvent);
      document.removeEventListener("mouseup", documentMouseupEvent);
    };
    return offEvents;
  }

  async function dragInit() {
    let content = document.getElementsByClassName("middle-content")[0];
    let baseMap = document.getElementsByClassName("base-map")[0];
    if (content && baseMap) {
      return eventsInit({ baseMap, content });
    } else {
      console.log("初始化失败");
      return await new Promise(resolve => {
        setTimeout(() => {
          const res = dragInit();
          resolve(res);
        }, 100);
      });
    }
  }
  onMounted(async () => {
    offEvents = await dragInit();
  });
  onBeforeUnmount(() => {
    if (offEvents) {
      offEvents();
      offEvents = null;
    }
  });
  return {
    dragInit
  };
};
export default useDrag;
